<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{

    //登录显示
    public function index(){
        //判断用户是否已经登录过
        if(auth()->check()){
            //跳转到后台首页
            return redirect(route('admin.index'));
        }
        return view('admin.login.login');
    }

    //登录 路由别名
    public function login(Request $request){
        //表单验证
        $post= $this->validate($request,[
            'username'=>'required',
            'password'=>'required'
        ],[
            'username.required'=>'账号都不想写,想飞了么?'
            ]
        );

        //登录
        $bool = auth()->attempt($post);
        if($bool){
            //登录成功
            //auth()->user() 返回当前登录的模型对象,存储在session中
            //laravel默认session是存储在文件中,优化到memcached redis
            //$model = auth()->user();
            //dump($model->toArray());

            //得到它的权限
            //判断一下是否是超级管理员
            if(config('rbac.super') != $post['username']){
                $userModel = auth()->user();
                $roleModel = $userModel->role;
                $nodeArr = $roleModel->nodes()->pluck('route_name','id')->toArray();
                //权限保持到session中
                session(['admin.auth'=>$nodeArr]);
            }else{
                session(['admin.auth'=> true]);
            }

            return redirect(route('admin.index'));
        }
        //withErrors 把错误信息
        return redirect(route('admin.login'))->withErrors(['error'=>'登录失败']);
    }



}
